/**
 * @format
 * @Author: TC
 * @Date: 2021-09-27 14:53:27
 * @Last Modified by: TC
 * @Last Modified time: 2025-06-20 22:22:34
 */

import { _decorator, Button, Component, Node } from "cc";
import { app } from "../../App";
import { EUILayer } from "../../Const/ComponentConst";
const { ccclass, property } = _decorator;

/**
 * 基础组件类
 */
@ccclass("BaseComponent")
export class BaseComponent extends Component {
    onLoad(): void {
        this.init();
        this.addUIEvent();
        this.registerEvent();
    }

    start() {}

    //初始化一些数据和UI
    protected init(): void {}

    /**
     * 注册UI事件
     */
    protected addUIEvent(): void {}
    /**
     * 删除UI事件
     */
    protected removeUIEvent(): void {}

    //添加监听
    protected registerEvent(): void {}

    /**
     * 注册事件
     * @param event
     * @param cb
     */
    protected register(event: string, cb: (param: unknown) => void): void {
        app.eventMgr.register(event, cb, this);
    }

    //移除监听
    protected unregisterEvent(): void {
        app.eventMgr.unregisterByTarget(this);
    }

    /**
     * 移除事件
     * @param event
     * @param cb
     */
    protected unregister(event: string): void {
        app.eventMgr.unregister(event, this);
    }

    /**
     * 派发事件
     * @param event
     * @param param
     */
    public dispatch(event: string, param: unknown): void {
        app.eventMgr.dispatch(event, param);
    }

    onEnable() {}

    /**
     * 从隐藏到显示
     */
    protected onShow(): void {}

    onDisable() {
        // this.onHide();
    }

    /**
     * 从隐藏到显示
     */
    public onHide(): void {}
    protected onRefresh() {}

    /**
     * 设置层级
     * @param layer
     */
    public setLayer(layer: EUILayer): void {
        const nodeLayer = app.sceneMgr.getCurrScene().getLayer(layer);
        this.node.setParent(nodeLayer);
    }

    /**
     * 置顶
     */
    public toTop(): void {
        this.node.setSiblingIndex(this.node.parent.children.length - 1);
    }

    /**
     * 置底
     */
    public toBottom(): void {
        this.node.setSiblingIndex(0);
    }

    /**
     * 添加点击事件
     * @param target
     * @param cb
     */
    protected addClickEvent(target: Node | Button, cb: () => void, param?: string): void {
        if (target instanceof Button) {
            if ("" == cb.name) {
                target.node.on(Node.EventType.TOUCH_END, cb, this);
                return;
            }
            const eventHandler = new Component.EventHandler();
            eventHandler.target = this.node;
            eventHandler.component = this.constructor.name;
            eventHandler.handler = cb.name;
            eventHandler.customEventData = param || "";
            target.clickEvents = [eventHandler];
        } else {
            target.on(Node.EventType.TOUCH_END, cb, this);
        }
    }
    onDestroy() {
        this.unscheduleAllCallbacks();
        this.unregisterEvent();
    }
}
